package com.tfswx.jkgl.designer.advice;

import com.alibaba.fastjson.JSON;
import com.tfswx.jkgl.designer.bean.JsonResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import springfox.documentation.spring.web.json.Json;
import springfox.documentation.swagger.web.SwaggerResource;

import java.util.List;
import java.util.Map;


/**
 * @author ricky
 * @date 2021/12/25
 */
@ControllerAdvice
public class DefaultResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(@NonNull MethodParameter methodParameter, @NonNull Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(@Nullable Object result, @NonNull MethodParameter methodParameter, @NonNull MediaType mediaType, @NonNull Class<? extends HttpMessageConverter<?>> aClass, @NonNull ServerHttpRequest serverHttpRequest, @NonNull ServerHttpResponse serverHttpResponse) {
        if (result instanceof Json) {
            return result;
        } else if (result instanceof JsonResult.ErrorResult) {
            return result;
        } else if (result instanceof JsonResult) {
            throw new RuntimeException("controller出参不正确，请勿使用JsonResult作为出参");
        } else if (result instanceof List) {
            List<?> list = (List<?>) result;
            if (!list.isEmpty() && (list.get(0) instanceof SwaggerResource)) {
                return result;
            }
        } else if (result instanceof String) {
            return JSON.toJSONString(JsonResult.success(result));
        } else {
            if (result instanceof Map) {
                Map<String, Object> map = (Map<String, Object>) result;
                Object code = map.get("code");
                if (code != null) {
                    return result;
                }
            }
        }
        return JsonResult.success(result);
    }
}

